package main

import (
	"net"
	"os"
	"fmt"
	"log"
)

func main() {

	//建立tcp连接
	netListen, err := net.Listen("tcp", "localhost:9998")
	checkErr(err)
	defer netListen.Close()


	log.Println("waiting for clients")
	for   {
		conn, err := netListen.Accept()
		if err != nil {
			log.Println("conn err:", err.Error())
			continue
		}

		log.Println("tcp connect success:", conn.RemoteAddr().String())
		go handleConn(conn)

	}

}

//处理链接
func handleConn(conn net.Conn)  {
	buffer := make([]byte, 1024)

	for {
		n, err := conn.Read(buffer)
		if err != nil {
			log.Println(conn.RemoteAddr().String()," conn read err:", err.Error())
			return
		}

		log.Println(conn.RemoteAddr().String(), "receive data string:\n", string(buffer[:n]))
	}
}



func checkErr(err error)  {
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fatal error:%s", err.Error())
		os.Exit(1)
	}
}